package toy.keli.edic.view

import android.os.Handler
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import toy.keli.edic.data.GlobalVal
import toy.keli.edic.data.config.BookConf
import toy.keli.edic.data.config.MenuConf
import toy.keli.edic.ui.home.HomeEvents
import toy.keli.edic.ui.home.WordModelViewModel
import toy.keli.edic.ui.home.WordState
import toy.keli.edic.ui.home.components.AutoCompleteTextField
import toy.keli.edic.ui.home.components.AutoCompleteTextFieldEvent
import toy.keli.edic.ui.home.viewMode
import toy.keli.edic.ui.listenbook.ListenBookData
import toy.keli.edic.ui.main.components.SearchButton
import toy.keli.edic.ui.main.extend.stringRun


@Composable
fun SearchTool(wordViewModel :WordModelViewModel){
    val keyboardController = LocalSoftwareKeyboardController.current
    var lastSugTime = System.currentTimeMillis()
    val search = SearchRun.getInstance()
    var canSug = remember { true }
    var visible by remember { GlobalVal.isSearchVisible }

    if(!visible) {
        SearchButton {
            HomeEvents.searchTools.show();
        }
    }else {
        val defaultText = HomeEvents.searchTools.defaultText;
        Row(
            modifier = Modifier
                .padding(15.dp)
                .alpha(0.9f)
//        .height(50.dp)
        ) {
            AutoCompleteTextField(
                text = defaultText,
                modifier = Modifier.fillMaxWidth(),
                suggestions = wordViewModel.suggestions,
                onSearch = {
                    //延迟执行 不要输入一次就搜索一次
                    if (canSug) {
                        search.onSug(it)
                        canSug = false
                    } else {
                        Handler().postDelayed({
                            if (System.currentTimeMillis() - lastSugTime > 450) {
                                canSug = true
                                search.onSug(it)
                            }
                        }, 500)
                    }
                    lastSugTime = System.currentTimeMillis()
                },
                onCancel = {
                    visible = false
                    search.onCancel()
                },
                onClear = {
                    search.onSug("")
                },
                //完成按钮单击
                onDoneActionClick = {
                    if(search.okClear && it.length>0) {
                        this.value =  TextFieldValue()
                        return@AutoCompleteTextField
                    }
                    //完成搜索的时候就隐藏输入框
                    if(search.onSearch(it)) {
                        keyboardController?.hide()
                        visible = false
                    }
                },
                //条目单击
                onItemClick = {
                    if(search.onSearch(it,false)) {
                        keyboardController?.hide()
                        visible = false
                    }
                },
                itemContent = {
//                    Text(
//                        text = it,
//                        color = MaterialTheme.colors.onSurface
//                    )
                }
            )
        }
    }
}

interface  SearchRun{
    val viewMode: MenuConf.mode
    val okClear:Boolean;        //单击完成按钮清楚显示
    fun onSug(s:String);
    fun onCancel();
    fun onSearch(s:String,isDone:Boolean=true):Boolean
    companion object{
        var _instance:SearchRun = WordSearch()
        fun getInstance(): SearchRun {
            if(_instance.viewMode == viewMode) return _instance
            _instance =when(viewMode){
                MenuConf.mode.showArticle->ArticleSearch()
                MenuConf.mode.wordStudy -> WordSearch()
                else -> _instance
            }
            return _instance
        }
    }
}
class ArticleSearch(override val viewMode:MenuConf.mode=MenuConf.mode.showArticle) :SearchRun{
    val wordViewModel = GlobalVal.wordViewModel;
    override val okClear: Boolean
        get() = false

    override fun onSug(s: String) {
        ListenBookData.instance.hasSugWord = true;
        wordViewModel.wordState.value = WordState(null)
        wordViewModel.prefixMatcher(s, onSugOver = {
        }) {
            wordViewModel.searcher(it, true)
            wordViewModel.detailState.value = true
            //延迟5s选中当前单词以备下次搜索输入
            stringRun(5000) {
                AutoCompleteTextFieldEvent.selectSearchKey()
            }
            true
        }
    }

    override fun onCancel() {
        ListenBookData.instance.hasSugWord = false;
    }

    override fun onSearch(s: String,isDone: Boolean): Boolean {
        if(!isDone){
            onSug(s)
            return false
        }
        wordViewModel.clearSuggestions()
        ListenBookData.instance.hasSugWord = false;
        wordViewModel.wordState.value = WordState(null)
        ListenBookData.searchKey(s)
        return false
    }

}
class WordSearch(override val viewMode: MenuConf.mode=MenuConf.mode.wordStudy) :SearchRun{
    var beforState: WordState?=null
    val wordViewModel = GlobalVal.wordViewModel;
    override val okClear: Boolean
        get() = wordViewModel.wordState.value.wordModel != null

    override fun onSug(it:String) {
        //如果是获取焦点则记录当前单词清空背景页
        if (it.length == 0) {
            if (beforState == null) {
                beforState = wordViewModel.wordState.value
                //wordViewModel.detailState.value = false
                wordViewModel.wordState.value = WordState(null)
            }else{
                wordViewModel.clearSuggestions()
            }
            return
        }
        wordViewModel.wordState.value = WordState(null)
        wordViewModel.prefixMatcher(it) {
            wordViewModel.searcher(it, true)
            true
        }
    }

    override fun onCancel(){
        //失去焦点如果没有搜索到单词则还原原始单词
        if (beforState != null && wordViewModel.wordState.value.wordModel == null) {
            wordViewModel.wordState.value = beforState as WordState
        }

        if (beforState != null
            && wordViewModel.wordState.value.wordModel != null
            && beforState!!.wordModel!!.word != wordViewModel.wordState.value.wordModel!!.word
        ) {
            //插入历史记录
            wordViewModel.insertHistory(wordViewModel.wordState.value.wordModel!!)
            //保证其他界面也有单词
            BookConf.instance.next(wordViewModel.wordState.value.wordModel!!)
        }
        beforState = null
    }
    //完成按钮单击
    override fun onSearch (it:String,isDone: Boolean): Boolean {
        val wordModel = wordViewModel.wordState.value.wordModel
        //如果当前界面没有单词则取第一个单词
        if(it.isEmpty() && wordViewModel.wordState.value ==null){
            wordViewModel.wordState.value = beforState!!;
        }else if(wordModel!=null && wordModel.word != it){
            wordViewModel.searcher(it, true)
        }else {
            wordViewModel.prefixMatcher(it, onMatch = {
                wordViewModel.searcher(it, true)
                true
            }, onNoMatch = {
                HomeEvents.searchTools.searchByOnline(it)
            });
        }
        beforState =null
        return true
    }
}